<template>
  <div :id="echartsId" style="width: 100%; height: 100%"></div>
</template>

<script>
import * as echarts from "echarts";
import { echartsToo, echartsLegend } from "@/util/echarts";

export default {
  name: "MyEchart",
  components: {},
  props: {
    opationDate: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      chart: null,
      echartsId: `echartsId${Math.random().toFixed(8)}`,
    };
  },
  watch: {
    opationDate(value) {
      /** 只允许渲染一次 */
      const { tooltip, legend } = { ...this.opationDate };
      if (tooltip) this.$set(this.opationDate, "tooltip", Object.assign(tooltip, echartsToo));
      if (legend) this.$set(this.opationDate, "legend", Object.assign(legend, echartsLegend));
      if (value) this.initChart(this.opationDate);
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart(this.opationDate);
    });
  },
  methods: {
    initChart(option) {
      this.chart = echarts.getInstanceByDom(document.getElementById(this.echartsId));
      if (this.chart == null) {
        this.chart = echarts.init(document.getElementById(this.echartsId));
      }
      this.chart.setOption(option);
      window.addEventListener("resize", () => {
        setTimeout(() => {
          this.chart.resize();
        }, 100);
      });
    },
  },
};
</script>
